//
//  LoginViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/9.
//

import UIKit
import RxSwift
import RxCocoa
class LoginViewController: UIViewController {
    private let bag = DisposeBag()
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var getCodeButton: UIButton!
    @IBOutlet weak var codeField: UITextField!
    @IBOutlet weak var checkPrivacyButton: UIButton!
    @IBOutlet weak var loginButton: UIButton!
    private let phone = BehaviorRelay<String>.init(value: "")
    private let code = BehaviorRelay<String>.init(value: "")
    private let agree = BehaviorRelay(value: true)
    
    @IBOutlet weak var containerView1: UIView!
    
    @IBOutlet weak var containerView2: UIView!
    
    var beginDate: Date?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
        // Do any additional setup after loading the view.
    }
    
    private func configView() {
        self.containerView1.layer.borderWidth = 1
        self.containerView1.layer.borderColor = UIColor.hex(with: "#126BFB").cgColor
        self.containerView2.layer.borderWidth = 1
        self.containerView2.layer.borderColor = UIColor.hex(with: "#126BFB").cgColor
        self.phoneField.rx.text.orEmpty.bind(to: self.phone).disposed(by: self.bag)
        self.phone.bind(to: self.phoneField.rx.text).disposed(by: self.bag)
        self.codeField.rx.text.orEmpty.bind(to: self.code).disposed(by: self.bag)
        self.code.bind(to: self.codeField.rx.text).disposed(by: self.bag)
        self.loginButton.setBackgroundImage(UIImage(named: "loan_agree_normal"), for: .normal)
        self.loginButton.setBackgroundImage(UIImage(named: "loan_agree_disable"), for: .disabled)
        self.checkPrivacyButton.setImage(UIImage(named: "login_agree_uncheck"), for: .normal)
        self.checkPrivacyButton.setImage(UIImage(named: "login_agree_check"), for: .selected)
        self.agree
            .bind(to: self.checkPrivacyButton.rx.isSelected)
            .disposed(by: self.bag)
        self.checkPrivacyButton.rx.tap
            .subscribe(onNext: { [weak self] event in
                let agree = !self!.agree.value
                self?.agree.accept(agree)
            })
            .disposed(by: self.bag)
        self.loginButton.titleLabel?.font = UIFont(name: "Righteous-Regular", size: 20)
        self.getCodeButton.setBackgroundImage(UIColor.color(with: 18, green: 107, blue: 251).image, for: .normal)
        self.getCodeButton.setTitleColor(UIColor.white, for: .normal)
        self.getCodeButton.setBackgroundImage(UIColor.color(with: 18, green: 107, blue: 251, alpha: 0.2).image, for: .disabled)
        self.getCodeButton.setTitleColor(UIColor.color(with: 18, green: 107, blue: 251), for: .disabled)
        self.getCodeButton.rx.tap
            .subscribe(onNext: { [weak self] event in
                self?.getSMSCode()
            })
            .disposed(by: self.bag)
        self.loginButton.rx.tap
            .subscribe(onNext: { [weak self] _ in
                self?.loginAction()
            })
            .disposed(by: self.bag)
    }
    
    
    private func getSMSCode() {
        Task {
            do {
                self.showLoading(text: nil)
                let res = try await HTTPManager.default.post(path: Api.getSMSCode, param: ["rounded": self.phone.value], dataType: [Int].self)
                self.hideLoading()
                if res.code == 0 {
                    if self.beginDate == nil {
                        self.beginDate = Date()
                    }
                    Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
                        .take(61)
                        .subscribe(onNext: { [weak self] time in
                            self?.getCodeButton.isEnabled = false
                            self?.getCodeButton.setTitle("\(59 - time)s".locale, for: .disabled)
                        }, onCompleted: {
                            self.getCodeButton.isEnabled = true
                        })
                        .disposed(by: self.bag)
                }
                self.show(toast: res.state)
            } catch {
                self.hideLoading()
                print(error)
            }
        }
    }
    
    private func loginAction() {
        if self.agree.value == false {
            self.show(toast: "Please read and agree to the Privacy Policy".locale)
            return
        }
        Task {
            do {
                struct LoginDataModel: Codable {
                    let madeira: String
                    let royally: String
                    let unhandsome: String
                }
                self.showLoading(text: nil)
                let res = try await HTTPManager.default.post(path: Api.login, param: ["madeira": self.phone.value, "britishly": self.code.value], dataType: LoginDataModel.self)
                if res.code == 0 {
                    UserDefaults.standard.set(res.data!.unhandsome, forKey: "session_id")
                    UploadStasticManager.default.uploadRiskPoint(type: 1, beginTime: self.beginDate)
                    self.hideLoading()
                    NotificationCenter.default.post(name: NSNotification.Name.init("kLoginSuccess"), object: nil)
                    self.dismiss(animated: false)
                    return
                }
                self.hideLoading()
                self.show(toast: res.state)
            } catch {
                self.hideLoading()
            }
        }
    }
    
    @IBAction func getVoiceCodeAction(_ sender: UIButton) {
        Task {
            do {
                self.showLoading(text: nil)
                let res = try await HTTPManager.default.post(path: Api.getVoiceCode, param: ["rounded": self.phone.value], dataType: [Int].self)
                self.show(toast: res.state)
                if res.code == 0 {
                    if self.beginDate == nil {
                        self.beginDate = Date()
                    }
                }
            } catch {
                self.hideLoading()
            }
        }
    }
    

    @IBAction func cancelAction(_ sender: Any) {
        self.dismiss(animated: false)
    }
    
    @IBAction func showPrivacyAction(_ sender: UIButton) {
        let agreementVC = LoanAgreementController()
        agreementVC.agree = self.agree
        self.alert(viewController: agreementVC)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
